/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.apache.rocketmq.console.controller;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.rocketmq.console.shiro.dao.UserInfoDao;
import org.apache.rocketmq.console.shiro.entity.UserInfo;
import org.apache.rocketmq.console.support.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserInfoDao userInfoDao;

	@RequestMapping(value = "/getCurentUser.query", method = RequestMethod.GET)
	@ResponseBody
	public Object getCurentUser() {
		UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
		Map<String, String> map = new HashMap<>();
		if (userInfo.getEmpName() == null) {
			map.put("name", userInfo.getName());
		} else {
			map.put("name", userInfo.getEmpName());
		}
		return map;
	}

	@RequestMapping(value = "/isShowEdit.query", method = RequestMethod.GET)
	@ResponseBody
	public Object isShowEdit() {
		Map<String, Boolean> map = new HashMap<>();
		UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
		int permissionId = userInfo.getPermissionId();
		if (permissionId == 1 || permissionId == 2) {
			map.put("isShowEdit", true);
		} else {
			map.put("isShowEdit", false);
		}
		return map;
	}
	@RequestMapping(value = "/adminShowEdit.query", method = RequestMethod.GET)
	@ResponseBody
	public Object adminShowEdit() {
		Map<String, Boolean> map = new HashMap<>();
		UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
		int permissionId = userInfo.getPermissionId();
		if (permissionId == 1) {
			map.put("adminShowEdit", true);
		} else {
			map.put("adminShowEdit", false);
		}
		return map;
	}

	// http://localhost:8081/user/addUser.do?name=show&pwd=show&permissionId=2&sysCode=UUMS
	@RequiresPermissions("rmq:admin") // 权限管理;
	@RequestMapping(value = "/addUser.do", method = RequestMethod.GET)
	@ResponseBody
	public Object addUser(@RequestParam String name, @RequestParam String pwd, @RequestParam int permissionId,
			@RequestParam String sysCode) {
		UserInfo findByName = userInfoDao.findByName(name);
		if (findByName == null) {
			UserInfo userInfo = new UserInfo();
			userInfo.setName(name);
			userInfo.setPassword(generatePwd(name, pwd));
			userInfo.setPermissionId(permissionId);
			List<String> sysCodes = new LinkedList<>();
			String[] sysCodeSplit = sysCode.split(",");
			for (String code : sysCodeSplit) {
				sysCodes.add(code);
			}
			userInfo.setSysCodes(JSON.toJSONString(sysCodes));
			userInfoDao.save(userInfo);
			return new JsonResult<UserInfo>(userInfo);
		} else {
			return new JsonResult<String>("用户已经存在");
		}

	}

	// http://localhost:8081/user/updateUser.do?name=show&pwd=show&permissionId=2&sysCode=BAMP
	@SuppressWarnings("unchecked")
	@RequiresPermissions("rmq:admin") // 权限管理;
	@RequestMapping(value = "/updateUser.do", method = RequestMethod.GET)
	@ResponseBody
	public Object updateUser(@RequestParam String name, @RequestParam String pwd, @RequestParam int permissionId,
			@RequestParam String sysCode) {
		UserInfo findByName = userInfoDao.findByName(name);
		if (findByName == null) {
			return new JsonResult<String>("用户不存在");
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setId(findByName.getId());
		userInfo.setName(name);
		userInfo.setPassword(generatePwd(name, pwd));
		userInfo.setPermissionId(permissionId);

		String sysCodes = findByName.getSysCodes();
		Set<String> sysCodesList = JSON.parseObject(sysCodes, Set.class);
		String[] sysCodeSplit = sysCode.split(",");
		for (String code : sysCodeSplit) {
			sysCodesList.add(code);
		}

		String sysCodesListJson = JSON.toJSONString(sysCodesList);

		userInfo.setSysCodes(sysCodesListJson);
		userInfoDao.save(userInfo);
		return new JsonResult<UserInfo>(userInfo);

	}

	public String generatePwd(String name, String pwd) {
		String hashAlgorithmName = "MD5";
		Object credentials = pwd;
		Object salt = ByteSource.Util.bytes(name);
		int hashIterations = 2;

		Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
		return result.toString();
	}

}
